#!/usr/bin/env node

/**
 * 强制清理所有 Node.js 进程（按PID逐个终止）
 *
 * 使用方法：
 *   node app/scripts/force-kill-node.mjs
 */

import { exec } from 'node:child_process'
import { promisify } from 'node:util'

const execAsync = promisify(exec)

async function forceKillAllNode() {
  console.log('='.repeat(80))
  console.log('强制清理所有 Node.js 进程')
  console.log('='.repeat(80))

  try {
    // 查找所有 node.exe 进程
    console.log('\n📋 查找所有 Node.js 进程...')
    const { stdout } = await execAsync('tasklist /FI "IMAGENAME eq node.exe" /FO CSV /NH')
    const lines = stdout.trim().split('\n').filter(line => line.trim())

    if (lines.length === 0) {
      console.log('✅ 没有找到 Node.js 进程')
      return
    }

    console.log(`\n找到 ${lines.length} 个 Node.js 进程:`)

    // 解析所有PID
    const pids = []
    for (const line of lines) {
      const parts = line.split(',').map(s => s.replace(/"/g, '').trim())
      if (parts.length >= 2) {
        const pid = parts[1]
        const memory = parts.length > 4 ? parts[4] : 'N/A'
        pids.push({ pid, memory })
        console.log(`  PID: ${pid.padStart(8)} | 内存: ${memory}`)
      }
    }

    console.log(`\n🔄 正在逐个终止进程...`)

    // 按PID逐个终止
    let successCount = 0
    let failCount = 0

    for (const { pid } of pids) {
      try {
        const { stdout, stderr } = await execAsync(`taskkill /F /PID ${pid} /T`, { timeout: 5000 })
        const output = (stdout || stderr || '').trim()

        if (output.includes('SUCCESS') || output.includes('成功')) {
          successCount++
          console.log(`  ✓ PID ${pid} 已终止`)
        }
        else {
          // 可能是进程已经不存在了
          successCount++
          console.log(`  ✓ PID ${pid} (可能已不存在)`)
        }
      }
      catch (error) {
        try {
          const errorMsg = error?.stderr || error?.message || ''
          const errorStdout = error?.stdout || ''
          const output = (errorStdout || errorMsg).trim()

          if (output.includes('SUCCESS') || output.includes('成功')) {
            // taskkill 的输出可能在 stderr，但实际成功了
            successCount++
            console.log(`  ✓ PID ${pid} 已终止`)
          }
          else if (output.includes('not found') || output.includes('找不到') || output.includes('不存在') || output.includes('不存在该进程')) {
            successCount++
            console.log(`  ✓ PID ${pid} (不存在)`)
          }
          else {
            failCount++
            // 不显示详细错误，避免输出过多
            console.log(`  ✗ PID ${pid} 终止失败 (继续处理下一个...)`)
          }
        }
        catch {
          // 捕获所有其他错误，继续处理下一个进程
          failCount++
          console.log(`  ✗ PID ${pid} 处理异常 (继续处理下一个...)`)
        }
      }

      // 短暂延迟，避免系统过载
      await new Promise(resolve => setTimeout(resolve, 100))
    }

    // 等待一下
    await new Promise(resolve => setTimeout(resolve, 2000))

    // 再次检查
    console.log('\n📋 检查剩余进程...')
    const { stdout: stdout2 } = await execAsync('tasklist /FI "IMAGENAME eq node.exe" /FO CSV /NH')
    const remainingLines = stdout2.trim().split('\n').filter(line => line.trim())
    const remaining = remainingLines.length

    console.log(`\n清理结果:`)
    console.log(`  成功终止: ${successCount} 个`)
    console.log(`  失败: ${failCount} 个`)
    console.log(`  剩余: ${remaining} 个`)

    if (remaining === 0) {
      console.log('\n✅ 所有 Node.js 进程已清理完成')
    }
    else {
      console.log('\n⚠️  仍有进程未清理，剩余进程:')
      for (const line of remainingLines) {
        const parts = line.split(',').map(s => s.replace(/"/g, '').trim())
        if (parts.length >= 2) {
          console.log(`  PID: ${parts[1]} | 内存: ${parts.length > 4 ? parts[4] : 'N/A'}`)
        }
      }
      console.log('\n建议:')
      console.log('  1. 以管理员身份运行 PowerShell')
      console.log('  2. 手动在任务管理器中终止这些进程')
      console.log('  3. 或者重启电脑')
    }
  }
  catch (error) {
    console.error('\n❌ 清理失败:', error)
    process.exit(1)
  }
}

forceKillAllNode().catch(console.error)
